package com.cls.business.service.impl;

import cn.hutool.core.date.DateUtil;
import com.cls.business.entity.*;
import com.cls.business.mapper.DeclareTopicMapper;
import com.cls.business.mapper.TopicPlanMapper;
import com.cls.business.service.IApplicantInfoService;
import com.cls.business.service.IBlackListService;
import com.cls.business.service.IMemberInfoService;
import com.cls.common.enums.DictEnum;
import com.cls.common.utils.StringUtils;
import com.cls.system.entity.ConfigureQualification;
import com.cls.system.service.IConfigureQualificationService;
import com.cls.system.service.ISysDictService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
@RequiredArgsConstructor
public class QualificationReviewService {
    private final static Logger LOG = LoggerFactory.getLogger(QualificationReviewService.class);

    @Autowired
    private IApplicantInfoService applicantInfoService;
    @Autowired
    private DeclareTopicMapper declareTopicMapper;
    @Autowired
    private TopicPlanMapper topicPlanMapper;
    @Autowired
    private IMemberInfoService memberInfoService;
    @Autowired
    private IConfigureQualificationService configureQualificationService;
    @Autowired
    private IBlackListService blackListService;

    private final ISysDictService sysDictService;

    // 包含行政职务、职称、学历
    private boolean checkProfessional(ApplicantInfo applicantInfo, ConfigureQualification qualification, StringBuilder builder) {
        boolean passed = false;
        String tip = "";
        if (qualification != null) {
            if (qualification.getDegreeTypeCode() != null && !passed) {
                if (applicantInfo.getDegreeTypeCode().compareTo(qualification.getDegreeTypeCode()) <= 0) {
                    passed = true;
                } else {
                    if (!tip.isEmpty()) {
                        tip += "或";
                    }
                    tip += "学位";
                }
            }
            if (qualification.getPositionTypeCode() != null) {
                if (applicantInfo.getPositionTypeCode().compareTo(qualification.getPositionTypeCode()) <= 0) {
                    passed = true;
                } else {
                    if (!tip.isEmpty()) {
                        tip += "或";
                    }
                    tip += "行政职务";
                }
            }
            if (qualification.getTitleTypeCode() != null) {
                if (applicantInfo.getTitleTypeCode().compareTo(qualification.getTitleTypeCode()) <= 0) {
                    passed = true;
                } else {
                    if (!tip.isEmpty()) {
                        tip += "或";
                    }
                    tip += "职称";
                }
            }
            if (!passed) {
                builder.append(tip + "不满足要求");
            }
        }
        return true;
    }

    // 包含年龄
    private boolean checkAge(ApplicantInfo applicantInfo,
                             ConfigureQualification qualification,
                             StringBuilder builder,
                             List<MemberInfo> memberInfos, String levelTypeCode) {
        if (applicantInfo == null || qualification == null) {
            return true;
        }
// 青年调研课题的主持人和课题组成员年龄都要进行检查限制
        boolean isQNDY = DictEnum.LEVEL_QNDY.getCode().equals(levelTypeCode);
        Date date = new Date();
        if (isQNDY && null != memberInfos) {
            for (MemberInfo memberInfo : memberInfos) {
                int ageFromIdentity = getAgeFromIdentity(memberInfo.getIdentity());
                if (ageFromIdentity == -1) {
                    builder.append(memberInfo.getName()).append("身份证号有误！");
                }
                long betweenYear = DateUtil.betweenYear(memberInfo.getBirthday(), date, false);
                if (qualification.getMaxAge() != null) {
                    if (betweenYear > qualification.getMaxAge()) {
                        builder.append("课题组成员：")
                                .append(memberInfo.getName())
                                .append("年龄：")
                                .append(ageFromIdentity)
                                .append("岁，超过限制年龄最大值！");

                    }
                }
                if (qualification.getMinAge() != null) {
                    if (betweenYear < qualification.getMinAge()) {
                        builder.append("课题组成员：")
                                .append(memberInfo.getName())
                                .append("年龄：")
                                .append(ageFromIdentity)
                                .append(" 岁，低于限制年龄最小值！");
                    }
                }

            }
        }
        int age = getAgeFromIdentity(applicantInfo.getIdentity());
        if (age == -1) {
            builder.append("身份证号有误！");
            return true;
        }
        long betweenYear = DateUtil.betweenYear(applicantInfo.getBirthday(), date, false);
        if (qualification.getMaxAge() != null) {
            if (betweenYear > qualification.getMaxAge()) {
                builder.append("超过限制年龄最大值！");
                return true;
            }
        }
        if (qualification.getMinAge() != null) {
            if (betweenYear < qualification.getMinAge()) {
                builder.append("低于限制年龄最小值！");
                return true;
            }
        }

        return true;
    }

    private int getAgeFromIdentity(String identity) {
        if (identity == null || identity.length() != 18) {
            return -1;
        }
        String birthday = identity.substring(6, 14);
        //当前日期
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        //计算年龄差
        Integer ageBit = Integer.parseInt(date) - Integer.parseInt(birthday);
        //当年龄差的长度大于4位时，即出生年份小于当前年份
        int age = 0;
        if (ageBit.toString().length() > 4) {//截取掉后四位即为年龄
            age = Integer.parseInt(ageBit.toString().substring(0, ageBit.toString().length() - 4));
        }
        return age;
    }

    // 课题主持人课题数量
    private boolean checkLeaderTopics(DeclareTopic declareTopic, StringBuilder builder) {
        Map<String, Object> param = new HashMap();
        param.put("applicant_id", declareTopic.getApplicantId());
        param.put("is_finish", false);
        List<DeclareTopic> declareTopics = declareTopicMapper.selectByMap(param);
        if (declareTopics != null && declareTopics.size() > 1) {
            builder.append(declareTopic.getLeaderName() + "已是一个项目的主持人；");
        }
        return true;
    }

    // 课题组成员课题数量
    private List<MemberInfo> checkMemberTopics(DeclareTopic declareTopic, StringBuilder builder) {
        MemberInfo param = new MemberInfo();
        param.setDeclareId(declareTopic.getDeclareId());
        List<MemberInfo> memberInfos = memberInfoService.findMemberInfos(param);
        if (memberInfos != null) {
            for (MemberInfo one : memberInfos) {
                int num = memberInfoService.getUnFinishNum(one.getIdentity());
                if (num > 2) {
                    builder.append(one.getName() + "已存在两个以上未结项；");
                }

            }
        }
        return memberInfos;
    }

    // 黑名单
    private boolean checkBlacklist(ApplicantInfo applicantInfo, StringBuilder builder) {
        if (applicantInfo == null || builder == null) {
            return false;
        }
        if (!StringUtils.isEmpty(applicantInfo.getIdentity())) {
            BlackList blackList = blackListService.findByIdentity(applicantInfo.getIdentity());
            if (blackList != null) {
                builder.append("主持人(" + blackList.getName() + ")在黑名单上;");
            }
        }
        return true;
    }

    public StringBuilder checkQualification(DeclareTopic declareTopic, Long planId) {
        StringBuilder builder = new StringBuilder();

        ApplicantInfo applicantInfo = applicantInfoService.getById(declareTopic.getApplicantId());
        // 黑名单
        checkBlacklist(applicantInfo, builder);

        // 成员参与课题情况
        List<MemberInfo> memberInfos = checkMemberTopics(declareTopic, builder);

        // 主持人参与课题情况
        checkLeaderTopics(declareTopic, builder);
        String levelTypeCode = declareTopic.getLevelTypeCode();


        TopicPlan plan = topicPlanMapper.selectById(planId);
        if (plan != null) {
            ConfigureQualification qualification = configureQualificationService.findByConfigureIdAndLevelType(plan.getConfigureId(), levelTypeCode);
            // 职称/职务要求
            checkProfessional(applicantInfo, qualification, builder);

            // 年龄限制
            checkAge(applicantInfo, qualification, builder, memberInfos, levelTypeCode);

            // 如果是西部扶持项目，判断人事关系所在地需要在一下几个地方否则提示信息
            if (DictEnum.LEVEL_XBFCXM.getCode().equals(levelTypeCode)) {
                Boolean condition = false;
                List<String> areas = Arrays.asList(qualification.getPersonnelAreaTypeCode().split(","));
                for (String dict : areas) {
                    if (dict.equals(applicantInfo.getPersonnelAreaTypeCode())) {
                        condition = true;
                    }
                }
                if (!condition) {
                    builder.append(applicantInfo.getName() + "的人事关系所在地非当前系统设置的西部扶持项目所在地;");
                }
            }
        }

        return builder;
    }

}
